/*
 * 
 * 
 * @author: Oren Zamir
 */
package org.valire.auth;

import java.io.Serializable;
import java.util.Iterator;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.valire.usermanagement.beans.Role;
import org.valire.usermanagement.services.MethodAccessControlService;


/**
 * The Class UserPermissionEvaluator.
 */
public class UserPermissionEvaluator implements PermissionEvaluator {

	/** The Method Access Control service. */
	@javax.annotation.Resource
	private MethodAccessControlService macService;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.security.access.PermissionEvaluator#hasPermission
	 * (org.springframework.security.core.Authentication, java.lang.Object,
	 * java.lang.Object)
	 */
	@Override
	public boolean hasPermission(Authentication authentication,
			Object targetDomainObject, Object permission) {
		
		Iterator<GrantedAuthority> iterator = authentication.getAuthorities().iterator();
		
		Role role = new Role();
		
		while (iterator.hasNext()) {
			GrantedAuthority ga = (GrantedAuthority) iterator.next();
			
			role.setRoleName(ga.getAuthority());
			
			if (macService.checkMethodAccessForRole(role,(String) permission))
				return true;
			
		}
			return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.security.access.PermissionEvaluator#hasPermission
	 * (org.springframework.security.core.Authentication, java.io.Serializable,
	 * java.lang.String, java.lang.Object)
	 * 
	 * @note - a handler is not implemented because it should never be called !!!!
	 */
	@Override
	public boolean hasPermission(Authentication authentication,
			Serializable targetId, String targetType, Object permission) {
		return false;
	}

}
